import os
import re
import subprocess
import tempfile
import uuid

from .table import Video

videoDir = tempfile.gettempdir()

class VideoDownloader:

    def downloader(self, url):
        video = Video()
        print("start download: %s" % url)
        filename = uuid.uuid1().hex
        try:
            content = subprocess.check_output(
                ["you-get", "-o", videoDir, "-O", filename,
                 "--no-caption", url,"--debug"])
            decodeContent = content.decode('utf-8')
            print(decodeContent)
            searchObj = re.search(
                r'site:\s*(.*)\ntitle:\s*(.*)\n[\s\S]*format:\s*(.*)\n[\s\S]*\((\d+) bytes\)[\s\S]*Downloading\s*(\S*)\s*',
                decodeContent)

            if not searchObj:
                searchObj = re.search(
                    r'Site:\s*(\S*)\nTitle:\s*([^\n]*)\nType:.*\(([^\n]*)\)\nSize.*\((\d+) Bytes\)[\s\S]*Downloading\s*(\S*)\s*',
                    decodeContent)
            if searchObj:
                obj = searchObj.groups()
                # print(searchObj.groups())
                video.site = obj[0]
                video.title = obj[1]
                video.type = obj[2]
                video.size = obj[3]
                video.path = os.path.join(videoDir, obj[4])
                video.link = url
                return video
        except subprocess.CalledProcessError as e:
            print(e)
